package com.aboo.design.strategy;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 策略模式：实现各种算法的封装，并能保障各算法策略间的切换
 */
public class StrategyPattern {
    public static void main(String[] args) {
        PayStrategy alipay = PayHandler.getPayStrategy("alipay");
        alipay.pay(new BigDecimal("58.88"));
        alipay.refund(new BigDecimal("2"));

        PayStrategy wechat = PayHandler.getPayStrategy("wechat");
        wechat.pay(new BigDecimal("36.66"));
        wechat.refund(new BigDecimal("5"));
    }
}

interface PayStrategy {

    String pay(BigDecimal money);

    String refund(BigDecimal money);

    String getChannel();
}

class AlipayStrategy implements PayStrategy {

    @Override
    public String pay(BigDecimal money) {
        System.out.println("采用支付宝支付，金额：" + money);
        return "alipay_pay_001";
    }

    @Override
    public String refund(BigDecimal money) {
        System.out.println("采用支付宝退款，金额：" + money);
        return "alipay_refund_001";
    }

    @Override
    public String getChannel() {
        return "alipay";
    }
}

class WechatStrategy implements PayStrategy {

    @Override
    public String pay(BigDecimal money) {
        System.out.println("采用微信支付，金额：" + money);
        return "wechat_pay_001";
    }

    @Override
    public String refund(BigDecimal money) {
        System.out.println("采用微信退款，金额：" + money);
        return "wechat_refund_001";
    }

    @Override
    public String getChannel() {
        return "wechat";
    }
}

class PayHandler {

    private static final Map<String, PayStrategy> PAY_CHANNEL = new ConcurrentHashMap<>(8);

    static {
        addPayStrategy(new AlipayStrategy());
        addPayStrategy(new WechatStrategy());
    }

    private static void addPayStrategy(PayStrategy payStrategy) {
        PAY_CHANNEL.put(payStrategy.getChannel(), payStrategy);
    }

    public static PayStrategy getPayStrategy(String channel) {
        return PAY_CHANNEL.get(channel);
    }
}